// pages/coin/coins/index.js
// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    steps: 1000,
    // 用户信息相关
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: true,
    canIUseOpenData: false
    // wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName')
    // 如需尝试获取用户信息可改为false
  },

  getUserProfile(e) {
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })

        this.getRunSetting()
      }
    })
  },

  /**
 * 用户授权读取微信运动数据
 */
  getRunSetting() {
    var that = this
    console.log("run setting")

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.werun']) {
          // 申请用户授权
          wx.authorize({
            scope: 'scope.werun',
            success() {
              that.getAllInfo()
            },
            fail() {
              wx.showModal({
                title: '读取失败',
                content: '请在小程序右上角[设置]中开启授权'
              })
            }
          })
        } else {
          that.getAllInfo()
        }
      }
    })
  },

  /**
   * 获取openid、sessionkey、encryptedData
   */
  getAllInfo() {
    var that = this
    
    var appId = 'wx6ad063cf9aa46a3c'
    var sessionKey = ''
    var encryptedData = ''
    var iv = ''

    wx.getWeRunData({
      success(res) {
        // 拿 encryptedData 到开发者后台解密开放数据
        encryptedData = res.encryptedData
        iv = res.iv
        console.log(res)

        wx.login({
          success(res) {
            if (res.code) {
              console.log(res.code)
              wx.request({
                url: 'https://api.weixin.qq.com/sns/jscode2session',
                data: {
                  appid: 'wx6ad063cf9aa46a3c',
                  secret: '55363249f30447da320deb90126ca62d',
                  js_code: res.code,
                  grant_type: 'authorization_code'
                },
                success: function (res) {
                  console.log(res.data)

                  sessionKey = res.data.session_key

                  that.postSteps(appId, sessionKey, encryptedData, iv)
                }
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      }
    })
  },


  /**
   * 上传微信步数
   */
  postSteps(appId, sessionKey, encryptedData, iv) {
    var that = this
    console.log("读取微信步数");
    console.log(appId)
    console.log(sessionKey)
    console.log(encryptedData)
    console.log(iv)

    wx.request({
      url: app.globalData.url + "/wxsteps_upload/",
      method: "POST",
      data: {
        userID: getApp().globalData.user.userId,
        plogTypeID: 1,
        appId: appId,
        sessionKey: sessionKey,
        encryptedData: encryptedData,
        iv: iv
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res.data)

        if (res.data.status_code == 200) {
          // wx.showToast({
          //   title: '今日步数已兑换',
          //   duration: 2000,
          //   mask: true
          // })
          wx.navigateTo({
            url: '../manageStep/index?message=' + res.data.message
          })
        } else if(res.data.status_code == 201){
          wx.showToast({
            title: '今天已上传过！',
            icon: 'error',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '步数不足兑换！',
            icon: 'error',
            duration: 2000
          })
        }


      },
      fail: function (res) {
        wx.showToast({
          title: '连接失败',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

  /**
   * 上传图片
   */
  getCoinsFromImages() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        wx.setStorage({
          key: 'imageUrl',
          data: res.tempFilePaths,
          success(res) {
            wx.navigateTo({
              url: '../uploadImage/index',
            })
          }
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '图片选择失败,请重新选择...',
          icon: 'none'
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})